package com.hmdp;

import lombok.extern.slf4j.Slf4j;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import javax.crypto.Cipher;
@Slf4j
public class RSAEncryption {

    public static void main(String[] args) throws Exception {
        String plaintext = "This is a secret message";

        // Generate RSA key pair
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024); // RSA key size can be 1024, 2048, or 4096 bits
        KeyPair keyPair = keyPairGen.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();// 公钥
        PrivateKey privateKey = keyPair.getPrivate();//私钥
        log.info("Public key: {}", publicKey);
        log.info("Private key: {}", privateKey);
        // Create Cipher instance and initialize it for encryption with the public key
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        // Encrypt plaintext
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());

        // Encode encrypted byte array to Base64 for transmission
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted text: " + encryptedText);

        // Decrypt encrypted text with the private key
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedBytes);

        System.out.println("Decrypted text: " + decryptedText);
    }
}
